package com.luhuiguo.contacts.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.inject.Inject;
import com.luhuiguo.contacts.shared.event.AddContactEvent;
import com.luhuiguo.contacts.shared.event.AddContactEventHandler;
import com.luhuiguo.gwt.presenter.client.EventBus;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerDisplay;
import com.luhuiguo.gwt.presenter.client.widget.WidgetContainerPresenter;

public class ContactsPresenter extends WidgetContainerPresenter<ContactsPresenter.Display> {

    public interface Display extends WidgetContainerDisplay {
        HasClickHandlers getAddButton();
    }

    private EditContactPresenter editContactPresenter;

    @Inject
    public ContactsPresenter(Display display, EventBus eventBus, EditContactPresenter editContactPresenter) {
        super(display, eventBus, editContactPresenter);
        this.editContactPresenter = editContactPresenter;
        GWT.log("ContactsPresenter created");
    }

    @Override
    protected void onBind() {
        GWT.log("ContactsPresenter onBind");
        super.onBind();
        registerHandler(eventBus.addHandler(AddContactEvent.TYPE, new AddContactEventHandler() {

            @Override
            public void onAddContact(AddContactEvent event) {
                showAddContact();
            }

        }));

        registerHandler(display.getAddButton().addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                eventBus.fireEvent(new AddContactEvent());
            }
        }));

    }

    @Override
    protected void onRevealDisplay() {
        GWT.log("ContactsPresenter onRevealDisplay");
    }

    @Override
    protected void onUnbind() {
        GWT.log("ContactsPresenter onUnbind");
    }

    private void showAddContact() {
        editContactPresenter.revealDisplay();
    }

}
